package com.bear.newsset.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import androidx.annotation.NonNull;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;

import com.bear.newsset.R;
import com.bear.newsset.entity.NewsDataEntity;
import com.bear.newsset.entity.NewsListEntity;
import com.bear.newsset.ui.activity.ContentActivity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.bear.newsset.ui.activity.ContentActivity.NAME_NEWS_SUB_ITEM_ENTITY;

/**
 * 工具类
 */
public class Utils {
    /**
     * 设置状态栏的文本颜色
     * @param mContext          上下文
     */
    public static void immersiveStatusBar(Context mContext, Window w) {
        int sdk = Build.VERSION.SDK_INT;
        //允许绘制状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        }

        /* 沉浸式 */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            w.clearFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS |
                            WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
            );
        }
        w.getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        );

        //版本适配
        if ( sdk >= Build.VERSION_CODES.LOLLIPOP ) {
            mContext.setTheme(R.style.HeightVerTheme);
            //透明状态栏
            w.setStatusBarColor(Color.TRANSPARENT);
        }else {
            mContext.setTheme(R.style.LowVerTheme);
        }
    }

    /**
     * 设置状态栏图标颜色
     * @param w         w
     * @param isBlack   是否为黑色
     */
    public static void setStatusBarIconColor(@NonNull Window w, boolean isBlack) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            View decorView = w.getDecorView();
            int vis = decorView.getSystemUiVisibility();
            if( isBlack ){
                vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else{
                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decorView.setSystemUiVisibility(vis);
            //上述代码对5.0无效，所以如果是黑色图标则状态栏颜色为黑色（黑色状态栏，白色字）
        }else if( isBlack && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
            w.setStatusBarColor(Color.BLACK);
        }
    }

    /**
     * 跳转到新闻内容页面
     * @param mContext  上下文
     * @param value     传入的参数值
     */
    public static void startContentActivity(Context mContext, NewsListEntity value) {
        startContentActivity(mContext, value.getItemData());
    }

    public static void startContentActivity(Context mContext, NewsDataEntity e) {
        Intent intent = new Intent();
        intent.setClass(mContext,ContentActivity.class);
        intent.putExtra(NAME_NEWS_SUB_ITEM_ENTITY, e);
        mContext.startActivity(intent);
    }

    /**
     * 将Objext转换为List<Map<String, String>
     * @param obj
     * @return
     */
    public static List<Map<String, String>> objectToList(Object obj) {
        String key, val;
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();

        if( obj instanceof List ) {
            List tmpList = (List) obj;
            //获取列表中的Map（现在是Obj，所以需要转换）
            for( Object mapObj : tmpList ) {
                /* 利用反射获取转换Map */
                Class<?> cls = mapObj.getClass();
                for( Field field : cls.getDeclaredFields() ) {
                    try {
                        field.setAccessible(true);
                        key = field.getName();
                        val = field.get(mapObj).toString();
                        map.put(key, val);
                    } catch (IllegalAccessException e) {
                        LogUtils.e("TAG", Arrays.toString(e.getStackTrace()));
//                        e.printStackTrace();
                        return null;
                    }
                }
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 就是单纯的去掉警告而已
     */
    public interface OnTouchListener { boolean onTouch(View v, MotionEvent event); }
    private static long downTime = -1;
    public static void setOnSuperTouchListener(View v, OnTouchListener listener) {
        v.setOnTouchListener((v1, event) -> {
            switch ( event.getAction() ) {
                case MotionEvent.ACTION_DOWN:
                    downTime = System.currentTimeMillis();
                    break;
                case MotionEvent.ACTION_UP:
                    long upTime = System.currentTimeMillis();
                    //不是长按时才触发优化，防止长按后抬起时触发一次点击事件
                    if( upTime - downTime < ViewConfiguration.getLongPressTimeout() ) {
                        v1.performClick();
                    }
                    downTime = -1;
                    break;
            }
            return listener.onTouch(v1, event);
        });
    }

//    /**
//     * json数组转二维字符串数组
//     * @param jsonArray         json数组
//     * @return
//     */
//    public static String[][] jsonArrToString2Arr(JSONArray jsonArray) {
//        LogUtils.e("TAG", "SSD:" + jsonArray.toJSONString());
//        String[][] str2Arr = new String[jsonArray.size()][];
//        JSONArray strArr;
//        //json转string[][]
//        for( int i = 0;i < jsonArray.size();i++ ) {
//            strArr = jsonArray.getJSONArray(i);
//            LogUtils.e("TAG", "SSD:a|" + jsonArray.size() + "|"+strArr.toJSONString());
//            for( int j = 0;j < strArr.size();j++) {
//                LogUtils.e("TAG", "SSD:b|" + j+"|" + strArr.size() + "|"+strArr.getString(j));
//                str2Arr[i][j] = strArr.getString(j);
//            }
//        }
//        return str2Arr;
//    }

    /**
     * px转dp
     * @param mContext      上下文
     * @param px            像素值
     * @return              返回的dp值
     */
    public static int px2Dp(Context mContext, int px) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * dp转px
     * @param mContext      上下文
     * @param dp            dip值
     * @return              返回的px值
     */
    public static int dp2Px(Context mContext, int dp) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }
}
